<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin\Permission;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PermissionController extends Controller
{

    public function index(Request $request)
    {
        if($request->isMethod('post')){
            $post = $request->input('delete');
            Permission::destroy($post);
            return redirect()->route('admin.permission')->with('status', 'success');
        }else {
            $res = ['title' => '我的'];
            //$res['user'] = Auth::user();
            $res['data'] = Permission::orderby('created_at','desc')->Paginate(4);
            return view('admin.permission.index', ['res' => $res]);
        }
    }

    public function add(Request $request)
    {
        if($request->isMethod('post')) {
            $permission = new Permission;
            $post = $permission->check($request);
            $permission->route = $post['route'];
            $permission->name = $post['name'];
            $permission->user_id = Auth::id();
            if($permission->save()){
                return redirect()->route('admin.permission')->with('status', 'success');
            }else{
                return back()->with('status', 'fail');
            }
        }else{
            $res=['title'=>'我的'];
            //$res['user']=Auth::user();
            return view('admin.permission.add',['res'=>$res]);
        }

    }

    public function edit(Request $request)
    {
        if($request->isMethod('post')) {
            $permission = Permission::find($request->id);
            $post = $permission->check($request);
            $permission->route = $post['route'];
            $permission->name = $post['name'];
            if($permission->save()){
                return redirect()->route('admin.permission')->with('status', 'success');
            }else{
                return back()->with('status', 'fail');
            }
        }else{
            $res=['title'=>'我的'];
            //$res['user']=Auth::user();
            $res['info'] = Permission::find($request->id);
            return view('admin.permission.edit',['res'=>$res]);
        }
    }

    public function del(Request $request)
    {
        $permission = Permission::find($request->id);
        $permission->delete();
        return redirect()->route('admin.permission')->with('status', 'success');
    }
}
